package source.view;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Point2D;

import javax.swing.JScrollPane;
import javax.swing.JViewport;

import source.model.Position;

/**
 * Provides a visual representation of the game world map with the currently visible units,
 * items, and structures on it.
 * @author Steve
 *
 */
public class AreaOverview extends JScrollPane{
	private ViewMap map;
	
	public AreaOverview(ViewMap map){
		super(map);
		this.map = map;
	}
	
	/**
	 * focusses the viewport on the currently selected tile.
	 */
	public void focusMap(){
		JViewport viewport = this.getViewport();
		Point vpt = viewport.getLocation();
		Point ptOfUnit = convertToPoint(map.transform(map.getSelectedTile()));
		
		Dimension scrollPaneSize = this.getPreferredSize();
		Dimension mapDim = map.getPreferredSize();
		
		if(mapDim.width < scrollPaneSize.width * 2 && mapDim.height < scrollPaneSize.height * 2){
			return;
		}
		
		Point newFocus = new Point(ptOfUnit.x - scrollPaneSize.width/2, ptOfUnit.y - scrollPaneSize.height/2) ;
		
		
		if(newFocus.x < 0 ){
			if(newFocus.y + scrollPaneSize.height > mapDim.height){
				newFocus.y = mapDim.height - scrollPaneSize.height;
			}
			else if(newFocus.y < 0){
				newFocus.y = 0;
			}
			newFocus.x = 0;
			viewport.setViewPosition(newFocus);
			this.setViewport(viewport);
		}
		else if(newFocus.y < 0){
			newFocus.y = 0;
			viewport.setViewPosition(newFocus);
			this.setViewport(viewport);
		}
		else if(newFocus.x + scrollPaneSize.width > mapDim.width){
			newFocus.x = mapDim.width - scrollPaneSize.width;
			viewport.setViewPosition(newFocus);
			this.setViewport(viewport);
		}
		else if(newFocus.y + scrollPaneSize.height > mapDim.height){
			newFocus.y = mapDim.height - scrollPaneSize.height;
			viewport.setViewPosition(newFocus);
			this.setViewport(viewport);
		}
		
		else if(newFocus.x > 0 && newFocus.y > 0){
			viewport.setViewPosition(newFocus);
			this.setViewport(viewport);
		}
	}
	
	/**
	 * returns the map.
	 * @return
	 */
	public ViewMap getMap(){
		return map;
	}
	
	private Point convertToPoint(Point2D pt){
		Point returnPt = new Point((int)pt.getX(), (int)pt.getY());
		return returnPt;
	}
}
